package com.avic.rong.userOrder.activity;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.BuildConfig;
import com.avic.rong.R;
import com.avic.rong.userOrder.DialogPhotoSelect;
import com.avic.rong.userOrder.event.InformUpdate;
import com.avic.rong.userOrder.api.UploadApi;
import com.avic.rong.userOrder.api.UploadPXApi;
import com.avic.rong.userOrder.api.UploadVoucherApi;
import com.avic.rong.userOrder.api.UploadVoucherPXApi;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SDCardUtils;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.customWedgit.SheetDialog;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.avic.rong.wedgit.permissionschecker.PermissionChecker;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.GlideApp;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.logger.Logger;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static com.avic.rong.activity.product.OnlineCServiceActivity.recycleBitmap;

public class UploadProofActivity extends BaseActivity{

    //权限
    private String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    @BindView(R.id.iv_upload_pic)
    ImageView ivUploadPic;
    @BindView(R.id.iv_default_pic)
    ImageView ivDefaultPic;
    @BindView(R.id.ll_upload_proof)
    LinearLayout llUploadProof;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;
    private DialogPhotoSelect dialogPhotoSelect;


    private String photoPath = null;
    private String order_id;
    private String orderType;
    private String order_sn;
    private SheetDialog sheetDialog;
    private PermissionChecker permissionChecker;

    private int TAKE_CAMERA_PHOTO = 200;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_upload_proof;
    }

    @Override
    protected void initView() {
        if (TextUtils.isEmpty(getIntent().getStringExtra("orderType"))) {
            finish();
        } else {
            order_id = getIntent().getStringExtra("order_id");
            orderType = getIntent().getStringExtra("orderType");
            order_sn = getIntent().getStringExtra("order_sn");
        }
        tvTitle.setText("支付凭证上传");
        ivDefaultPic.setVisibility(View.VISIBLE);
        ivUploadPic.setVisibility(View.GONE);
        loading_layout.setStatus(LoadingLayout.SUCCESS);
        permissionChecker = new PermissionChecker(this);
    }

    private void submitProof(String pic) {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            map.put("orderId", order_id);
            map.put("token", getSharedPreferencesUtil().getLogintoken());
            map.put("tempUrl", pic);
            final UploadVoucherApi uploadVoucherApi = new UploadVoucherApi(this, simpleOnNextListenerSubmit);
            uploadVoucherApi.setCache(false);
            uploadVoucherApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(uploadVoucherApi);


        }
    }

    @Override
    protected void addListener() {
        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        final RxPermissions permissions = new RxPermissions(this);
        llUploadProof.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFileChooser();
            }
        });
        tvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(photoPath)){
                    ToastTools.showToast(UploadProofActivity.this,"请选择支付凭证截图");
                    return;
                }
                if (Integer.parseInt(orderType) != 5) {
                    upLoadProof(photoPath);
                } else {
                    upLoadProofPX(photoPath);
                }

            }
        });

    }

    //弹窗
    private void showFileChooser(){
        sheetDialog =  new SheetDialog.Builder(this).setTitle(ConstantsUtils.EMPTY_STR)
                .addMenu("拍照", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (sheetDialog != null && sheetDialog.isShowing()){
                            sheetDialog.dismiss();
                        }
                        if (permissionChecker.isLackPermissions(PERMISSIONS)) {
                            permissionChecker.requestPermissions();
                        } else {
                            photoPath = SDCardUtils.getSDCardPath() + "/temp.png";
                            File file = new File(photoPath);
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(UploadProofActivity.this, BuildConfig.APPLICATION_ID + ".provider", file));
                            }else{
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                            }

                            intent.putExtra("return-data", false);
                            intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
                            intent.putExtra("noFaceDetection", true);
                            startActivityForResult(intent, TAKE_CAMERA_PHOTO);
                        }
                    }
                })
                .addMenu("从相册中选择", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (sheetDialog != null && sheetDialog.isShowing()){
                            sheetDialog.dismiss();
                        }
                        if (permissionChecker.isLackPermissions(PERMISSIONS)) {
                            permissionChecker.requestPermissions();
                        } else {
                            startPickPhoto();
                        }
                    }
                }).setCancelListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sheetDialog.dismiss();
                    }
                }).create();
        sheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });
        sheetDialog.show();
    }

    //选择照片
    private void startPickPhoto(){

        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
//                    .maxSelectNum(3)
                .maxSelectNum(1)
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(3)// 每行显示个数
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isCamera(false)// 是否显示拍照按钮
                .isZoomAnim(false)// 图片列表点击 缩放效果 默认true
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .glideOverride(260, 260)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }


    private void upLoadProofPX(String photoPath) {
        if (photoPath != null) {
            UploadPXApi uploadPXApi = new UploadPXApi(this, simpleOnNextListenerPX);

            File file = new File(photoPath);
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);

            MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
            uploadPXApi.setPart(part);
            HttpManager.getInstance().doHttpDeal(uploadPXApi);
            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(uploadPXApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    onBackPressed();
                }
            });
            loading_layout.setStatus(LoadingLayout.LOADING);
        } else {
            loading_layout.setStatus(LoadingLayout.EMPTY);
        }
    }

    private void upLoadProof(String photoPath) {

        if (photoPath != null) {
            UploadApi uploadApi = new UploadApi(this, simpleOnNextListener);

            File file = new File(photoPath);
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);

            MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
            uploadApi.setPart(part);
            HttpManager.getInstance().doHttpDeal(uploadApi);
            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(uploadApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    onBackPressed();
                }
            });
            loading_layout.setStatus(LoadingLayout.LOADING);
        } else {
            loading_layout.setStatus(LoadingLayout.EMPTY);
        }

    }

    //上传图像
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(UploadProofActivity.this, subjects.getMsg());
                return;
            }
            String pic = (String) subjects.getData();
            if (!TextUtils.isEmpty(pic)) {
                //            提交凭证
                submitProof(pic);
            }
        }


        @Override
        public void onCacheNext(String cache) {
        }

        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };
    //上传图像
    HttpOnNextListener simpleOnNextListenerPX = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(UploadProofActivity.this, subjects.getMsg());
                return;
            }
            String pic = (String) subjects.getData();
            if (!TextUtils.isEmpty(pic)) {
                // 培训提交凭证
                submitProofPX(pic);
            }
        }

        @Override
        public void onCacheNext(String cache) {
        }

        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    private void submitProofPX(String pic) {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            map.put("orderNumber", order_sn + "");
            map.put("token", getSharedPreferencesUtil().getLogintoken());
            map.put("tempUrl", pic);
            final UploadVoucherPXApi uploadVoucherPXApi = new UploadVoucherPXApi(this, simpleOnNextListenerSubmitPX);
            uploadVoucherPXApi.setCache(false);
            uploadVoucherPXApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(uploadVoucherPXApi);
        }
    }

    //上传支付凭证
    HttpOnNextListener simpleOnNextListenerSubmit = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(UploadProofActivity.this, subjects.getMsg());
                return;
            }
            ToastTools.showToast(UploadProofActivity.this, "上传成功");
            loading_layout.setStatus(LoadingLayout.SUCCESS);
            InformUpdate informUpdate = new InformUpdate();
            informUpdate.setEventType(informUpdate.SUBMIT_PROOF_INFORM);
            EventBus.getDefault().post(informUpdate);
            finish();

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    //培训上传支付凭证
    HttpOnNextListener simpleOnNextListenerSubmitPX = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(UploadProofActivity.this, subjects.getMsg());
                return;
            }
            ToastTools.showToast(UploadProofActivity.this, "上传成功");
            loading_layout.setStatus(LoadingLayout.SUCCESS);
            InformUpdate informUpdate = new InformUpdate();
            informUpdate.setEventType(informUpdate.SUBMIT_PROOF_INFORM);
            EventBus.getDefault().post(informUpdate);
            finish();

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    //相机相册回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == TAKE_CAMERA_PHOTO){//拍照
//                ToastTools.showToast(OnlineCServiceActivity.this,"asdfasdf" + cameraPath);
                compressPictureUpload(photoPath);
            }else if(requestCode == PictureConfig.CHOOSE_REQUEST){//选择照片

                // 图片选择结果回调
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                List<LocalMedia> tempList = PictureSelector.obtainMultipleResult(data);
                for (LocalMedia media : tempList) {
                    if (media.isCompressed()) {
                        Logger.i("图片-----》", media.getCompressPath());
                        photoSelectResult(media.getCompressPath());
                    }
                }
//                ToastTools.showToast(OnlineCServiceActivity.this,"asddddddddddd");
            }
            sheetDialog.cancel();
        }
    }

    //压缩并上传图片
    private Bitmap bitmap;
    private File uploadFile;
    private void compressPictureUpload(String imagePath){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        bitmap = BitmapFactory.decodeFile(imagePath, options);

        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                uploadFile = compressImage(bitmap);
                emitter.onNext(uploadFile.getAbsolutePath());
            }
        }).subscribeOn(Schedulers.computation()).observeOn(Schedulers.newThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String temp) throws Exception {
                photoSelectResult(temp);
                recycleBitmap(bitmap);
            }
        });
    }

    /**
     * 压缩图片（质量压缩）
     * @param bitmap
     */
    public static File compressImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 5 * 1024 && options > 10) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            Logger.i("-----------------------------option:" + options);
            if (options > 0) {//options 的范围为0--100
                bitmap.compress(Bitmap.CompressFormat.PNG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            }
            long length = baos.toByteArray().length;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File file = new File(Environment.getExternalStorageDirectory(), filename + ".png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                Logger.e(e.getMessage());
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            Logger.e(e.getMessage());
            e.printStackTrace();
        }
        recycleBitmap(bitmap);
        return file;
    }

    public void photoSelectResult(String path) {
        photoPath = path;
        File file = new File(path);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                GlideApp.with(context).load(file).into(ivUploadPic);
                ivDefaultPic.setVisibility(View.GONE);
                ivUploadPic.setVisibility(View.VISIBLE);
            }
        });
    }

}
